package server.requesthandler;

import entity.Message;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * @author 14548
 */
public class ServerChatMessageHandler extends SimpleChannelInboundHandler<Message> {
    private static ChannelGroup channelGroup =
            new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
        System.out.println("chatmessage 收到请求");
        //dataContent->ChatMsg
        //chatMsg -> jsonString
        System.out.println(msg.getMsg());
        Channel channel = ctx.channel();
        channelGroup.forEach(ch -> {
            ch.writeAndFlush(msg);
        });
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
//        if(evt instanceof IdleStateEvent) {
//            Channel channel = ctx.channel();
//            IdleStateEvent event = (IdleStateEvent) evt;
//            if(event.state() == IdleState.READER_IDLE) {
//                System.out.println(channel.remoteAddress() + "读空闲");
//            }else if(event.state() == IdleState.WRITER_IDLE) {
//                System.out.println(channel.remoteAddress() + "写空闲");
//            }else if(event.state() == IdleState.ALL_IDLE) {
//                System.out.println(channel.remoteAddress() + "读写空闲");
//            }
//        }
        super.userEventTriggered(ctx, evt);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.add(channel);
        System.out.println("一个客户端上线了:" + channel.remoteAddress());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        System.out.println("一个客户端下线了:"+channel.remoteAddress());
    }
}
